<template>
  <div class="login-wrapper">
    <!-- 登录页容器 -->
    <div class="login-box">
      <!-- 宣传图片区域 -->
      <div class="promo-image">
        <img src="@/assets/picture/111.png" alt="宣传图" />
      </div>
      <!-- 登录表单区域 -->
      <div class="register-page">
        <h2>登录</h2>
        <form @submit.prevent="handleLogin">
          <div class="form-group">
            <label for="phone_num">手机号</label>
            <input
              type="text"
              v-model="phone_num"
              id="phone_num"
              placeholder="请输入手机号"
              required
            />
          </div>
          <div class="form-group">
            <label for="password">密码</label>
            <input
              type="password"
              v-model="password"
              id="password"
              placeholder="请输入密码"
              required
            />
          </div>
          <div class="form-group">
            <label for="imageCode">验证码</label>
            <div style="display: flex; gap: 10px; align-items: center">
              <input
                type="text"
                v-model="imageCode"
                id="imageCode"
                placeholder="请输入验证码"
                required
                style="flex: 1;width: 155px;"
              />
              <img 
                :src="captchaSrc" 
                alt="验证码" 
                style="height: 40px; cursor: pointer; border: 1px solid #ccc"
                @click="fetchCaptcha"
              />
            </div>
          </div>
          <div style="margin-left:60px;margin-bottom:20px">
            <input
              type="checkbox"
              id="rememberMe"
              v-model="rememberMe"
            />
            <label for="rememberMe" style="color: #555555;
              font-size: 14px;
              text-align: left;">记住我
              </label>
          </div>
          <button type="submit">登录</button>
          <p>还没有账号？<router-link to="/register">去注册</router-link></p>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import api from '@/services/api';
import { ElMessage } from 'element-plus';
export default {
  name: 'LoginPage',
  setup(props, { emit }) {
    const phone_num = ref('');
    const password = ref('');
    const rememberMe = ref(false);
    const router = useRouter();
    const imageCode = ref(''); 
    const captchaSrc = ref(''); 
    const captchaCode = ref('');
    const fetchCaptcha = async () => {
      try {
        const response = await api.get('/youxich/user/getImageCode');
        // 解析新数据结构
        captchaSrc.value = `data:image/png;base64,${response.data.data.imageBase64}`;
        captchaCode.value = response.data.data.imageCode.toLowerCase(); // 存储正确验证码（转为小写）
      } catch (error) {
        console.error('获取验证码失败:', error);
        ElMessage.error('验证码获取失败');
      }
    };

    // 检查是否有存储的用户信息
    onMounted(() => {
      fetchCaptcha(); 
      const storedRememberMe = localStorage.getItem('rememberMe') === 'true';
      if (storedRememberMe) {
        const storedPhone = localStorage.getItem('phone_num') || '';
        const storedPassword = localStorage.getItem('password') || '';
        phone_num.value = storedPhone;
        password.value = storedPassword;
        rememberMe.value = storedRememberMe;
      } else {
        const sessionPhone = sessionStorage.getItem('phone_num') || '';
        const sessionPassword = sessionStorage.getItem('password') || '';
        phone_num.value = sessionPhone;
        password.value = sessionPassword;
      }
    });

    const handleLogin = async () => {
      try {
        if (imageCode.value.toLowerCase() !== captchaCode.value) {
          ElMessage.error('验证码错误');
          return fetchCaptcha(); // 刷新验证码
        }
        const response = await api.post('/youxich/user/login', {
          phone_num: phone_num.value,
          password: password.value,
        });

        if (response.data && response.data.status === 1) {
          const { id, token, username, img_url, user_type, lastlogin_time } = response.data.data;
          const storage = rememberMe.value ? localStorage : sessionStorage;

          storage.setItem('id', id);
          storage.setItem('token', token);
          storage.setItem('username', username);
          storage.setItem('userAvatar', img_url);
          storage.setItem('userRole', user_type);
          storage.setItem('lastLoginTime', lastlogin_time);

          if (rememberMe.value) {
            localStorage.setItem('phone_num', phone_num.value);
            localStorage.setItem('password', password.value);
            localStorage.setItem('rememberMe', 'true');
          } else {
            sessionStorage.setItem('phone_num', phone_num.value);
            sessionStorage.setItem('password', password.value);
            localStorage.setItem('rememberMe', 'false');
          }

          emit('loginSuccess', user_type || '', img_url || '', username || '', id || '');
          router.push('/');
          ElMessage.success('登录成功!');
        } else {
          alert(response.data.msg);
        }
       } catch (error) {
        console.error('登录失败:', error);
        ElMessage.error('登录失败，请检查手机号和密码');
      }
    };

    return {
      phone_num,
      password,
      rememberMe,
      imageCode,
      captchaSrc,
      handleLogin,
      fetchCaptcha
    };
  }
};
</script>

<style scoped>
/* 外层容器，确保页面中央悬挂 */
.login-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 85vh;
  background-image: url('https://plus.unsplash.com/premium_photo-1670176446913-ca025ebaf172?q=80&w=2069&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D');
}

/* 登录页的整体盒子，包含图片和表单 */
.login-box {
  display: flex;
  max-width: 800px;
  width: 100%;
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 0 0 12px rgba(66, 185, 131, 0.6); /* 边缘发光效果 */
  overflow: hidden;
  animation: floatUpAndDown 3s ease-in-out infinite; /* 上下浮动动画 */
  transition: box-shadow 0.3s ease, transform 0.3s ease;
}

.login-box:hover {
  animation-play-state: paused; /* 鼠标悬停时停止动画 */
  box-shadow: 0 0 20px 5px rgba(255, 255, 255, 0.8); /* 鼠标悬停时增加发光效果 */
}


/* 上下浮动动画 */
@keyframes floatUpAndDown {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px); /* 浮动高度 */
  }
}

/* 宣传图片区域 */
.promo-image {
  flex: 1;
  background-color:#78889d; /* 为图片区域添加背景色 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.promo-image img {
max-width: 100%;
    height: 115%;
    object-fit: cover;
}

/* 登录表单区域 */
.register-page {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 200px;
}

/* 标题样式 */
.register-page h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333333;
  font-size: 24px;
  font-weight: bold;
}

/* 表单组 */
.form-group {
  margin-bottom: 20px;
  display: flex; /* 新增：启用弹性布局 */
  align-items: center; /* 新增：垂直居中 */
  gap: 15px; /* 新增：元素间距 */
}


/* 标签样式 */
.form-group label {
  flex: 0 0 50px; /* 修改：固定标签宽度 */
  margin-bottom: 0; /* 移除原有下边距 */
  color: #555555;
  font-size: 14px;
  text-align: left; /* 新增：文字右对齐 */
}

/* 输入框和选择框样式 */
.form-group input,
.form-group select {
  flex: 1; /* 修改：占据剩余空间 */
  padding: 10px 12px;
  border: 1px solid #cccccc;
  border-radius: 5px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group select:focus {
  border-color: #42b983;
  outline: none;
  transform: scale(1.02); /* 获取焦点时的放大效果 */
  box-shadow: 0 0 5px rgba(66, 185, 131, 0.5); /* 阴影效果 */
}
.form-group > div { /* 新增：验证码输入行容器 */
  flex: 1;
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 记住我复选框样式 */
.form-group.remember-me {
  display: flex;
  align-items: center;
}

.form-group.remember-me input {
  width: auto;
  margin-right: 8px;
}

.form-group.remember-me label {
  margin: 0;
  font-size: 14px;
  color: #555555;
}

/* 提交按钮样式 */
button {
  width: 100%;
  padding: 12px;
  background-color: #143874;
  color: #ffffff;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  transition: transform 0.3s ease, background-color 0.3s; /* 添加按钮悬停动画 */
}

button:hover {
  background-color: #2d579c;
}

/* 链接样式 */
.register-page p {
  text-align: center;
  margin-top: 20px;
  color: #666666;
  font-size: 14px;
}

.register-page a {
  color: #2d579c;
  text-decoration: none;
  font-weight: bold;
}

.register-page a:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-box {
    flex-direction: column;
    max-width: 90%;
  }

  .promo-image {
    display: none; /* 隐藏图片区域，保持在小屏幕上表单更简洁 */
  }
}

@media (max-width: 480px) {
  .register-page {
    padding: 20px;
  }

  .register-page h2 {
    font-size: 20px;
  }

  button {
    font-size: 14px;
    padding: 10px;
  }
}
</style>
